import axios from 'axios';
import { message } from 'antd';
import 'antd/lib/message/style';

// 设置全局请求
axios.defaults.baseURL = '/api';

// GET POST
function ajax (url, method = 'GET', params = {}, config = {}) {
  return new Promise((resolve) => {
    if (method === 'GET') {
      axios.get(url, params)
        .then(({ data }) => {
          resolve(data);
        })
        .catch((e) => {
          // 全局处理异常
          message.error(e.message);
        });
    } else if (method === 'POST') {
      axios.post(url, params, config)
        .then(({ data }) => {
          resolve(data);
        })
        .catch((e) => {
          // 全局处理异常
          message.error(e.message);
        });
    }
  });
}

// ALL
export const  all = function  (promise) {
  return new Promise((resolve) => {
    axios.all(promise)
      // 逐个获取返回结果，...list将返回结果封装入集合中
      .then(axios.spread((...list) => {
        resolve(list)
      }))
      .catch((e) => {
        message.all('并发请求错误: ' + e)
      })
  })
}

// GET请求
export const GET = (url, params) => ajax(url, 'GET', params);

// POST请求
export const POST = (url, params, config) => ajax(url, 'POST', params, config);

